<?php
/***
* @version $Id: functions_admin.php 336 2007-01-23 08:12:56Z flexiondotorg $
* @copyright (c) 2006 - 2007 Flexion.Org
*            (c) 2004 - 2006 OXPUS < webmaster@oxpus.de > (Karsten Ude) http://www.oxpus.de
*            (c) 2004 - 2005 Project Minerva
*            (c) 2003             Nivisec (support@nivisec.com) http://www.nivisec.com
*            (c) 2001 - 2006 phpBB Group
* @license   http://opensource.org/licenses/gpl-license.php GNU Public License
***/

if (!defined('IN_R3BORN'))
{
	die('Hacking attempt');
}

function jr_admin_check_file_hashes($file, $mv_name)
{
    global $root_path, $phpEx, $userdata, $module;

    //Include the file to get the module list
    $setmodules = 1;

	if ($mv_name != '')
	{
		include($root_path . 'modules/' . $mv_name . '/admin/' . $file . '.' . $phpEx);
	}
	else
	{
		include($root_path . 'admin/' . $file);
	}
    unset($setmodules);

    $jr_admin_userdata = jr_admin_get_user_info($userdata['user_id']);

    $user_modules = explode('|', $jr_admin_userdata['user_jr_admin']);

    foreach($module as $cat => $module_data)
    {
        foreach($module_data as $module_name => $module_file)
        {
            //Remove sid if we find one
            $module_file = preg_replace("/(\?|&|&amp;)sid=[A-Z,a-z,0-9]{32}/", '', $module_file);
            //Make our unique ID
            $file_hash = md5($cat . $module_name . $module_file);
            //See if it is in the array
            if (in_array($file_hash, $user_modules))
            {
                return true;
            }
        }
    }

    //If we get this far, the user has no business with the module filename
    return false;
}

function jr_admin_get_module_list($user_module_list = false)
{
    global $root_path, $phpEx, $userdata, $mvModules;

	$module = array();

    //Read all the core ACP modules
    $setmodules = 1;
    $dir = @opendir($root_path . 'admin/');
    $pattern = "/^admin_.+\.$phpEx$/";
    while (($file = @readdir($dir)) !== false)
    {
        if (preg_match($pattern, $file))
        {
            include($root_path . 'admin/' . $file);
        }
    }
    @closedir($dir);

	// Read all the ACP modules from enabled blocks/modules.
    foreach ($mvModules as $name => $value)
    {
	    if ($value['state'] == MODULE_ENABLED || $value['state'] == MODULE_DEFAULT)
	    {
        	foreach ($value['admin'] as $n => $file)
        	{
            	@include($root_path . 'modules/' . $name . '/admin/' . $file);
        	}
		}
    }

    unset($setmodules);

    @ksort($module);

    //Get the cache list we have and find non-existing and new items
    foreach ($module as $cat => $item_array)
    {
        foreach ($item_array as $module_name => $filename)
        {
            //Remove sid in case it was appended too early *(cough admin_disallow.php cough)*
            $filename = preg_replace("/(\?|&|&amp;)sid=[A-Z,a-z,0-9]{32}/", '', $filename);

            //Note the md5 function compilation here to make a unique id
            $file_hash = md5($cat . $module_name . $filename);

            //Wee a 3-D array of our info!
            if ($user_module_list && $userdata['user_level'] != ADMIN)
            {
                //If we were passed a list of valid modules, make sure we are sending the correct list back
                $user_modules = explode('|', $user_module_list);
                if (in_array($file_hash, $user_modules))
                {
                    $module_list[$cat][$module_name]['filename'] = $filename;
                    $module_list[$cat][$module_name]['file_hash'] = $file_hash;
                }
            }
            else
            {
                //No list sent?  Send back all of them because we should be an ADMIN!
                $module_list[$cat][$module_name]['filename'] = $filename;
                $module_list[$cat][$module_name]['file_hash'] = $file_hash;
            }
        }
    }

    return $module_list;
}

function jr_admin_secure($file, $module_name)
{
    global $phpEx, $userdata;

    $jr_admin_userdata = jr_admin_get_user_info($userdata['user_id']);

    if ($userdata['user_level'] == ADMIN)
    {
        //Admin always has access
        return true;
    }
    elseif (empty($jr_admin_userdata['user_jr_admin']))
    {
        //This user has no modules and no business being here
        return false;
    }
    elseif (preg_match("/^index.$phpEx/", $file))
    {
        //We are at the index file, which is already secure pretty much
        return true;
    }
    elseif (isset($_GET['module_md5']) && in_array($_GET['module_md5'], explode('|', $jr_admin_userdata['user_jr_admin'])))
    {
        //The user has access for sure by module_id security from GET vars only
        return true;
    }
    elseif (!isset($_GET['module_md5']) && count($_POST))
    {
        //This user likely entered a post form, so let's use some checking logic
        //to make sure they are doing it from where they should be!

        //Get the filename without any arguments
        $file = preg_replace("/\?.+=.*$/", '', $file);
        //Return the check to make sure the user has access to what they are submitting
        return jr_admin_check_file_hashes($file, $module_name);
    }
    elseif (!isset($_GET['module_md5']) && isset($_GET['sid']))
    {
        //This user has clicked on a url that specified items
        if ($_GET['sid'] != $userdata['session_id'])
        {
            return false;
        }
        else
        {
            //Get the filename without any arguments
            $file = preg_replace("/\?.+=.*$/", '', $file);
            //Return the check to make sure the user has access to what they are submitting
            return jr_admin_check_file_hashes($file, $module_name);
        }
    }
    else
    {
        //Something came up that shouldn't have!
        return false;
    }
}

function jr_admin_make_info_box()
{
    global $template, $lang, $userdata, $config;

    if ($userdata['user_level'] != ADMIN)
    {
        $jr_admin_userdata = jr_admin_get_user_info($userdata['user_id']);

        $template->set_filenames(array('JR_ADMIN_INFO' => 'jr_admin_user_info_header.tpl'));

        $template->assign_vars(array(
        'JR_ADMIN_START_DATE' => create_date($config['default_dateformat'], $jr_admin_userdata['start_date'], $config['board_timezone']),
        'JR_ADMIN_UPDATE_DATE' => create_date($config['default_dateformat'], $jr_admin_userdata['update_date'], $config['board_timezone']),
        'JR_ADMIN_ADMIN_NOTES' => $jr_admin_userdata['admin_notes'],
        'L_JR_ADMIN_TITLE' => $lang['Junior_Admin_Info'],
        'L_MODULE_COUNT' => $lang['Module_Count'],
        'L_NOTES' => $lang['Notes'],
        'L_ALLOW_VIEW' => $lang['Allow_View'],
        'L_START_DATE' => $lang['Start_Date'],
        'L_UPDATE_DATE' => $lang['Update_Date'],
        'L_ADMIN_NOTES' => $lang['Admin_Notes']
        ));

        //Switch the info area if allowed to view it
        if ($jr_admin_userdata['notes_view'])
        {
            $template->assign_block_vars('jr_admin_info_switch', array());
        }

        $template->assign_var_from_handle('JR_ADMIN_INFO_TABLE', 'JR_ADMIN_INFO');
    }
}

function page_header_admin()
{
	global $template, $db, $lang, $config, $root_path, $phpEx, $theme;

	define('HEADER_INC', true);

	//
	// gzip_compression
	//
	if ( $config['gzip_compress'] && extension_loaded('zlib') )
	{
		ob_start('ob_gzhandler');
	}

	$template->set_filenames(array(
		'header' => 'page_header.tpl')
	);

	// Format Timezone. We are unable to use array_pop here, because of PHP3 compatibility
	$l_timezone = explode('.', $config['board_timezone']);
	$l_timezone = (count($l_timezone) > 1 && $l_timezone[count($l_timezone)-1] != 0) ? $lang[sprintf('%.1f', $config['board_timezone'])] : $lang[number_format($config['board_timezone'])];

	//
	// The following assigns all _common_ variables that may be used at any point
	// in a template. Note that all URL's should be wrapped in append_sid, as
	// should all S_x_ACTIONS for forms.
	//
	$template->assign_vars(array(
		'SITENAME' => $config['sitename'],

		'L_ADMIN' => $lang['Admin'],
		//'L_INDEX' => sprintf($lang['Forum_Index'], $config['sitename']),
		'L_INDEX' => $lang['Home'],
		'L_HELP' => $lang['Help'],

		'U_INDEX' => append_sid('../index.'.$phpEx),

		'S_TIMEZONE' => sprintf($lang['All_times'], $l_timezone),
		'S_LOGIN_ACTION' => append_sid('../login.'.$phpEx),
		//	'S_JUMPBOX_ACTION' => append_sid('../viewforum.'.$phpEx),
		'S_CURRENT_TIME' => sprintf($lang['Current_time'], create_date($config['default_dateformat'], time(), $config['board_timezone'])),
		'S_CONTENT_DIRECTION' => $lang['DIRECTION'],
		'S_CONTENT_ENCODING' => $lang['ENCODING'],
		'S_CONTENT_DIR_LEFT' => $lang['LEFT'],
		'S_CONTENT_DIR_RIGHT' => $lang['RIGHT'],
		'U_PNGFIX_JS' => $root_path . 'javascript/pngfix.js',
		'STYLESHEET' => $theme['head_stylesheet'],
		)
	);

	header('Cache-Control: private, no-cache="set-cookie", pre-check=0, post-check=0');
	header('Expires: 0');
	header('Pragma: no-cache');

	$template->pparse('header');
}

function page_footer_admin()
{
	global $template, $db, $userdata, $lang, $config;

	//
	// Show the overall footer.
	//
	$template->set_filenames(array(
		'page_footer' => 'page_footer.tpl')
	);

	$template->assign_vars(array(
		'R3BORN_VERSION' => ($userdata['user_level'] == ADMIN && $userdata['user_id'] != ANONYMOUS) ? $config['version'] : '',
		'TRANSLATION_INFO' => (isset($lang['TRANSLATION_INFO'])) ? $lang['TRANSLATION_INFO'] : ((isset($lang['TRANSLATION'])) ? $lang['TRANSLATION'] : ''))
	);

	$template->pparse('page_footer');

	//
	// Close our DB connection.
	//
	$db->sql_close();
	exit;
}

?>